/* eslint-disable */
import React, { useEffect, useState } from 'react';
import { Divider, Button, Card, Form, Row, Col, Input, Select, InputNumber, Spin, message } from 'antd';
import styles from './PerformingPartiesManagement.less';
import ApprovalHistoryQuery from "../../common/ApprovalHistoryQuery";
import CounterpartyChooseRadio from "../../common/CounterpartyChooseRadio";
import OrganizationChooseRadio from "../../common/OrganizationChooseRadio";
import { formatNoFixed, debounce } from '../../../utils/commonUtil';
import moment from 'moment';
import { SearchOutlined } from '@ant-design/icons';
import img from "../../../assets/logo-loading.gif"
import { addOrUpdateBadTrader, updateStatusBadTrader } from '../../../services/credit/performingPartiesManagementServicey';
const { Option } = Select;
const FormItem = Form.Item;
const { TextArea, Search } = Input;

const PerformingPartiesApply = (props) => {

  const { operateType, addSave, onCounterparty, onCancel, historicalRecordModalVisible, historicalRecordModalLoading, onOrganizationChooseRadioCancel, onSearch, onCancelSon,
    historicalRecordModalList, onCancelModel, examinationApprovalStatus, frozenType, performingPartiesManagementInfoData, modalType, onHistoricalRecord, orgChooseList,
    onSubmit, counterpartyModalVisible, counterpartyLoading, counterpartyList, counterpartyCurrentPage, counterpartyPageSize, counterpartyTotal, onOrganizationChooseRadio,
    onReset, onPageChange, onShowSizeChange, organizationChooseRadioVisible, onOrganizationChooseRadioShowSizeChange, organizationChooseRadioTotal, getOverdueAmount,
    organizationChooseRadioLoading, organizationChooseRadioList, organizationChooseRadioCurrentPage, organizationChooseRadioPageSize, overdueAmount, idFlag, edit,
    onOrganizationChooseRadioSearch, onOrganizationChooseRadioPageChange, onOrganizationChooseRadioReset, dispatch } = props;
  const [form] = Form.useForm();
  const { validateFields, setFieldsValue, resetFields, getFieldsValue } = form;
  const [spinFlag, useSpinFlag] = useState(false)
  const frozenTypeOptions = frozenType.map(item => <Option key={item.dictSubCode} value={item.dictSubCode}>{item.dictValue}</Option>);
  const examinationApprovalStatusOptions = examinationApprovalStatus.map(item => <Option key={item.dictSubCode} value={item.dictSubCode}>{item.dictValue}</Option>);

  const onAdd = (flag) => {
    validateFields().then(values => {
      if (operateType == "add" && idFlag) {
        values.id = idFlag
      }
      values.applicationType = modalType == "freeze" ? 1 : 2
      addOrUpdateBadTrader(values).then(res => {
        if (res.code == 200 || res.code == 201) {
          message.info("成功！");
          dispatch({ type: "performingPartiesManagementModel/updateState", payload: { idFlag: values.id ? values.id : res.data } });
          if (flag) {
            updateStatusBadTrader({ id: values.id ? values.id : res.data }).then(data => {
              if (data.code == 200 || data.code == 201) {
                onCancel()
              } else {
                message.info(data.error);
              }
              useSpinFlag(false)
            })
          } else {
            useSpinFlag(false)
          }
        } else {
          message.info("失败！");
          useSpinFlag(false)
        }
      })
    }).catch(error => {
      useSpinFlag(false)
    });
  }

  useEffect(() => {
    if (operateType) {
      performingPartiesManagementInfoData.applyForTime = moment(performingPartiesManagementInfoData.applyForTime).format('YYYY-MM-DD')
      resetFields()
      setFieldsValue(performingPartiesManagementInfoData)
      dispatch({ type: "performingPartiesManagementModel/updateState", payload: { affiliatedInstitution: performingPartiesManagementInfoData.affiliatedInstitution, } });
    }
  }, [operateType])

  useEffect(() => {
    if (overdueAmount) {
      setFieldsValue({
        currentArrears: overdueAmount
      })
    }
  }, [overdueAmount])

  const approvalHistoryQueryProps = {
    historicalRecordModalVisible,
    historicalRecordModalLoading,
    historicalRecordModalList,
    receiptNumber: getFieldsValue().receiptNumber,
    onCancelModel
  };

  const counterpartyChooseProps = {
    counterpartyModalVisible, onCancelSon, onSearch, onReset, counterpartyLoading, counterpartyList, counterpartyCurrentPage, counterpartyPageSize, counterpartyTotal,
    onPageChange, onShowSizeChange,
    onSave: (key, rows) => {
      setFieldsValue({
        counterpartyName: rows[0].counterpartyName,
        masterDataCode: rows[0].masterDataCode,
      })
      onCancelSon()
      onChange()
    }
  }

  const organizationChooseRadioProps = {
    organizationChooseRadioPageSize, organizationChooseRadioTotal, onOrganizationChooseRadioReset, onOrganizationChooseRadioSearch, onOrganizationChooseRadioPageChange,
    onOrganizationChooseRadioShowSizeChange, orgChooseList, organizationChooseRadioList, organizationChooseRadioLoading,
    organizationChooseRadioCurrentPage, organizationChooseRadioVisible, onOrganizationChooseRadioCancel,
    organizationAdd: (key, row) => {
      setFieldsValue({
        affiliatedInstitutionName: row[0].orgName,
        affiliatedInstitution: key.join(","),
        counterpartyName: "",
        masterDataCode: "",
      })
      dispatch({ type: "performingPartiesManagementModel/updateState", payload: { affiliatedInstitution: key.join(","), } });
      onOrganizationChooseRadioCancel()
    }
  };

  const onChange = () => {
    if (modalType == "thaw" && getFieldsValue().masterDataCode && getFieldsValue().affiliatedInstitution) {
      getOverdueAmount({ masterDataCode: getFieldsValue().masterDataCode, affiliatedInstitution: getFieldsValue().affiliatedInstitution })
    }
  }

  // const onSubmitFlag = () => {
  //   validateFields().then(values => {
  //     if (operateType == "add" && idFlag) {
  //       values.id = idFlag
  //     }
  //     values.applicationType = modalType == "freeze" ? 1 : 2
  //     onSubmit(values, () => { useSpinFlag(false); onCancel() })
  //   }).catch(error => { useSpinFlag(false) });
  // }

  // const debounAddceFun = debounce(onAdd, 1000)
  // const debounSubmitceFun = debounce(onSubmitFlag, 1000)

  return (
    <Spin spinning={spinFlag} indicator={<div style={{ height: "50px", width: "37px", top: "40%", margin: "-30px" }}>
      <img src={img}></img>
    </div>}>
      <Card style={{ marginBottom: "16px" }}>
        <div className={styles.toolbarText} style={{ marginBottom: "0" }}>
          <div>{modalType == "thaw" ? "交易方解冻申请" : "交易方冻结申请"}</div>
          <div>
            <Button style={{ marginRight: '15px' }} onClick={() => onHistoricalRecord({ receiptNumber: getFieldsValue().receiptNumber })} >审批历史记录查询</Button>
            <Button style={{ marginRight: '15px' }} onClick={() => onCancel()} >返回</Button>
            <Button style={{ marginRight: '15px' }} onClick={() => { useSpinFlag(true); onAdd(false) }}
              disabled={(operateType == "view" && edit) || (performingPartiesManagementInfoData.status != "new" && performingPartiesManagementInfoData.status != "denied")}>保存</Button>
            <Button disabled={(operateType == "view" && edit) || (performingPartiesManagementInfoData.status != "new" && performingPartiesManagementInfoData.status != "denied")}
              type="primary" onClick={() => { useSpinFlag(true); onAdd(true) }}>提交</Button>
          </div>
        </div>
      </Card>
      <Card>
        <Divider orientation="left">基础信息</Divider>
        <Form form={form} layout={"vertical"} initialValues={performingPartiesManagementInfoData}>
          <Row gutter={20}>
            <Col span={0}>
              <FormItem label="交易方名称" name={"id"}>
                <Input />
              </FormItem>
            </Col>
            <Col span={0}>
              <FormItem label="交易方名称" name={"receiptNumber"}>
                <Input />
              </FormItem>
            </Col>
            <Col span={0}>
              <FormItem label="交易方名称" name={"masterDataCode"} rules={[{ required: true, message: '请选择交易方名称' }]}>
                <Input />
              </FormItem>
            </Col>
            <Col span={0}>
              <FormItem label="归属机构" name={"affiliatedInstitution"} rules={[{ required: true, message: '请输入归属机构' }]}>
                <Input />
              </FormItem>
            </Col>
            <Col span={8}>
              <FormItem label="归属机构" name={"affiliatedInstitutionName"} rules={[{ required: true, message: '请输入归属机构' }]}>
                <Search autoComplete="off" onSearch={() => { onOrganizationChooseRadio(getFieldsValue().affiliatedInstitution) }}
                  onClick={() => { onOrganizationChooseRadio(getFieldsValue().affiliatedInstitution) }}
                  disabled={(operateType == "view" && edit) || (operateType == "view" && performingPartiesManagementInfoData.status != "new")} />
              </FormItem>
            </Col>
            <Col span={8}>
              <FormItem label="交易方名称" name={"counterpartyName"} rules={[{ required: true, message: '请选择交易方名称' }]} >
                <Search autoComplete="off" onSearch={() => onCounterparty(modalType, getFieldsValue().affiliatedInstitution)}
                  onClick={() => onCounterparty(modalType, getFieldsValue().affiliatedInstitution)}
                  disabled={(operateType == "view" && edit) || (operateType == "view" && performingPartiesManagementInfoData.status != "new")} />
              </FormItem>
            </Col>
            <Col span={8}>
              <FormItem label="状态" name={"status"}>
                <Select disabled>
                  {examinationApprovalStatusOptions}
                </Select>
              </FormItem>
            </Col>
            <Col span={modalType == "thaw" ? 0 : 8} >
              <FormItem label="冻结原因类型" name={"causesOfFreezing"} rules={[{ required: modalType == "thaw" ? false : true, message: '请选择冻结原因类型' }]}>
                <Select placeholder="冻结原因类型" disabled={(operateType == "view" && edit) || (operateType == "view" && performingPartiesManagementInfoData.status != "new")} >
                  {frozenTypeOptions}
                </Select>
              </FormItem>
            </Col>
            <Col span={8} >
              <FormItem label="申请时间" name={"applyForTime"}>
                <Input disabled />
              </FormItem>
            </Col>
            <Col span={modalType == "thaw" ? 0 : 8} >
              <FormItem label="欠款金额（元）" name={"amountsOwed"} rules={[{ required: modalType == "thaw" ? false : true, message: '请输入欠款金额（元）' }]}>
                <InputNumber placeholder="请输入欠款金额（元）" style={{ width: "100%" }} formatter={value => value ? formatNoFixed(value,) : ''}
                  disabled={(operateType == "view" && edit) || (operateType == "view" && performingPartiesManagementInfoData.status != "new")} />
              </FormItem>
            </Col>
            <Col span={modalType == "freeze" ? 0 : 8}>
              <FormItem label="当前逾期金额" name={"currentArrears"}>
                <InputNumber disabled style={{ width: "100%" }} formatter={value => value ? formatNoFixed(value,) : ''} />
              </FormItem>
            </Col>
            <Col span={16}>
              <FormItem label={modalType == "thaw" ? "申请解冻原因" : "申请冻结原因"} name={"applyForReason"}
                rules={[{ required: true, message: modalType == "thaw" ? "请输入申请解冻原因" : "请输入申请冻结原因" }]}>
                <TextArea placeholder={modalType == "thaw" ? "请输入申请解冻原因" : "请输入申请冻结原因"}
                  disabled={(operateType == "view" && edit) || (operateType == "view" && performingPartiesManagementInfoData.status != "new")} />
              </FormItem>
            </Col>
            <Col span={modalType == "thaw" ? 0 : 8} >
              <FormItem label="逾期天数（天）" name={"overdueDays"} rules={[{ required: modalType == "thaw" ? false : true, message: '请输入逾期天数（天）' }]}>
                <InputNumber placeholder="请输入逾期天数（天）" style={{ width: "100%" }}
                  disabled={(operateType == "view" && edit) || (operateType == "view" && performingPartiesManagementInfoData.status != "new")} />
              </FormItem>
            </Col>
          </Row>
        </Form>
      </Card>
      <ApprovalHistoryQuery {...approvalHistoryQueryProps} />
      <CounterpartyChooseRadio {...counterpartyChooseProps} />
      <OrganizationChooseRadio {...organizationChooseRadioProps} />
    </Spin>
  );
}

export default PerformingPartiesApply;
